#!/usr/bin/python

# python-resmon - Python tools for Resmon monitoring and the Circonus API
# Copyright (c) 2010 Crown coypright
# 
# This file is part of python-resmon.
# 
# python-resmon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# python-resmon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with python-resmon.  If not, see <http://www.gnu.org/licenses/>.


"""Iterate through all metrics, changing the contact group """

import re
from circonus.api import CirconusAPI, APIError

# Contact groups to add to all metrics
CG_ADD = [(1, 'Emergency Response')]
CG_REMOVE = [(1, 'SMS'), (1, 'Sysadmin Phone')]

c = CirconusAPI.from_config()

contact_groups = {}

def get_contact_group(name):
    try:
        return contact_groups[name]
    except KeyError:
        cg = c.find_contact_group_by_name(name)
        contact_groups[name] = cg
        return cg


for chk in c.list_checks():
    if not re.search(r'\(resmon:.*?\)$', chk.name):
        continue

    for m in chk.list_metrics():
            for severity, cg_name in CG_ADD:
                contact_group = get_contact_group(cg_name)
                try:
                    m.add_contact_group(contact_group, severity=severity)
                except APIError, e:
                    # don't care, assuming the error is this known string
                    if e.message() == 'that contact group has already been added to this rule and severity':
                        continue
                    elif e.message() == 'could not find rule':
                        continue
                    else:
                        raise
                else:
                    print chk.name, m.name, "added", cg_name

            for severity, cg_name in CG_REMOVE:
                contact_group = get_contact_group(cg_name)
                try:
                    m.remove_contact_group(contact_group, severity=severity)
                except APIError, e:
                    # don't care, assuming the error is this known string
                    if e.message() == 'could not find rule':
                        continue
                    else:
                        raise
